from flask import request, jsonify




def get_image():
    base64img = request.form.get("image")
    project_path = r"D:\\Program Files\\JetBrains\\PyCharm 2021.3.3\\pythonProject\\woZaiFlaskProject"
    save_name = project_path + r"\\resource\\upload.jpg"
    transBase64ToFile(base64img, save_name)

# 将基于base64编码的图片去掉前缀后解码并保存
def transBase64ToFile(base64img, fileSavePath):
    import base64
    imgdata = base64img.split(';base64,')[1]
    imgdata = base64.b64decode(imgdata)
    with open(fileSavePath, "wb") as f:
        f.write(imgdata)
        f.close()

# POST
# 用户点击了发送日记按钮，后端将数据存储下来
def storeDiaryToDatabase():
    from Pojo import Diary
    from Pojo import db
    import datetime
    from Controller.login.getJWTandVerify import getUidFromToken
    from Service import calculateDiaryScore
    diaryContent = request.form.get("diaryContent")
    selectImagePids = request.form.get("selectImagePids")
    selectemo = request.form.get("diaryEmo")
    user_token = request.headers.get('Authorization')
    insert_did = Diary.query.count() + 1
    try:
        diarycreatedate = datetime.date.today().strftime("%Y-%m-%d")
        diarycreatedatetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        diary1 = Diary(
            content = diaryContent,
            images = selectImagePids,
            createdate = diarycreatedate,
            createtime = diarycreatedatetime,
            fuid = int(getUidFromToken(user_token)),
            diaryscore = calculateDiaryScore(diaryContent, selectemo),
            diaryemo = selectemo,
            )
        db.session.add(diary1)
        db.session.commit()
        return "发送成功"
        # insertLargeNumberOfDiary()
    except:
        db.session.rollback()
        return "上传日记失败"

# 非实用接口，只是为了在数据库中塞入假的数据
def insertLargeNumberOfDiary():
    from Pojo import Diary
    from Pojo import db

    emo_score_map = {'angel': '5', 'angry': '5', 'blink': '25', 'confused': '10', 'cool-1': '20', 'cool': '25',
                     'corpse': '5', 'cry-1': '10', 'cry': '10', 'devil': '15', 'dizzy': '10', 'expressionless-1': '20',
                     'expressionless': '15', 'fall-ill': '15', 'haha-1': '20', 'haha': '20', 'happy-1': '15',
                     'happy-2': '20', 'happy-3': '20', 'injured': '5', 'jealous': '25', 'kiss-1': '25', 'kiss-2': '25',
                     'kiss': '25', 'laughcry': '25', 'love': '25', 'lue-1': '20', 'lue-2': '25', 'lue': '20',
                     'mask': '15', 'muddleb': '20', 'mute': '15', 'poisoning-1': '5', 'poisoning': '10', 'sad-1': '5',
                     'sad-2': '10', 'shocked-1': '15', 'beshocked': '20', 'shut-up': '10', 'sleep': '15',
                     'sly-smile': '25', 'smile-1': '5', 'squint': '10', 'sweating': '5', 'thinking': '10',
                     'tired': '10', 'worry-1': '15', 'worry': '15', 'yue-1': '5', 'yue': '5'}

    try:
        import random
        import datetime
        from test import read_file
        from datetime import timedelta
        from Service import calculateDiaryScore
        one_day = timedelta(days=1)
        fake_start = datetime.datetime(2021, 12, 3)
        fake_end = datetime.datetime(2021, 12, 30)
        sentences = read_file()
        it = iter(sentences)
        diary_list = []
        while fake_start != fake_end:
            # try:
            diarycreatedate = fake_start.strftime("%Y-%m-%d")
            diarycreatedatetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            diaryContent = str(next(it))
            # print(diaryContent)
            selectemo = ''
            random_id = random.randint(0, len(emo_score_map)-1)
            for i, (k, v) in enumerate(emo_score_map.items()):
                if i == random_id:
                    selectemo = k
                    break
            if selectemo == '':
                selectemo='angry'

            try:
                fake_score = calculateDiaryScore(diaryContent, selectemo)
            except:
                fake_score = random.randint(20, 96)

            try:
                diary1 = Diary(
                    content=diaryContent,
                    images='',
                    createdate=diarycreatedate,
                    createtime=diarycreatedatetime,
                    fuid=1,
                    diaryscore=fake_score,
                    diaryemo=selectemo,
                )
                diary_list.append(diary1)
            except:
                print("创建失败啊啊啊啊啊啊啊啊啊")
                pass
            fake_start +=  one_day
        print(diary_list)
        db.session.add_all(diary_list)
        db.session.commit()
        return "创建日记的所有配置都弄好了。。。"
    except:
        print("没成功")
        db.session.rollback()
        return "上传日记失败"

# GET
# 接口接受到请求之后的操作，对请求中的参数进行解析
def selectDiaryByDate():
    from Controller.login.getJWTandVerify import getUidFromToken
    user_token = request.headers.get('Authorization')
    qy_date = request.args.get('qyDate')
    try:
        tmp = slelectDiaryByDateAndUid(qy_date, int(getUidFromToken(user_token)))
        rtn_list = []
        for i in tmp:
            pre_dict = {
                'did': i.did,
                'mood_type': i.diaryemo,
                'diary_content': i.content,
                'update_time': i.createtime.strftime("%Y-%m-%d %H:%M:%S")
            }
            rtn_list.append(pre_dict)

        # print(tmp)
        return jsonify({
            'diarys': rtn_list
        })
    except:
        print(slelectDiaryByDateAndUid(qy_date, int(getUidFromToken(user_token))))
        return "Token无效"

# POST
# 将图片保存到数据库中
def storeImageToDatabase():
    from Pojo import Image
    from Pojo import db
    from Controller.login.getJWTandVerify import getUidFromToken

    # 请求头中的Token
    user_token = request.headers.get('Authorization')
    base64img = request.form.get("base64image")
    insert_pid = Image.query.count() + 1
    # insert_pid = 100
    try:
        img1 = Image(pid = insert_pid, fuid=int(getUidFromToken(user_token)), image = base64img)
        db.session.add(img1)
        db.session.commit()
        return str(insert_pid)
    except:
        db.session.rollback()
        return '500'

# GET
def getSingleDiary():
    from Controller.login.getJWTandVerify import getUidFromToken
    user_token = request.headers.get('Authorization')
    qy_did = request.args.get('diaryDid')
    try:
        qr_diary = selectDiaryByDid(qy_did, int(getUidFromToken(user_token)))
        images_list = [int(e) if e.isdigit() else e for e in qr_diary.images.split(',')]
        return jsonify({
            'did': qr_diary.did,
            'content': qr_diary.content,
            'images': images_list,
            'createdate': qr_diary.createdate.strftime("%Y-%m-%d"),
            'createtime': qr_diary.createtime.strftime("%Y-%m-%d %H:%M:%S"),
            'fuid': qr_diary.fuid,
            'diaryscore': qr_diary.diaryscore,
            'diaryemo': qr_diary.diaryemo,
        })
    except:
        print(selectDiaryByDid(qy_did, int(getUidFromToken(user_token))))
        return "Token无效"

# GET
# 获取单个图片
def getSingleImage():
    from Controller.login.getJWTandVerify import getUidFromToken
    user_token = request.headers.get('Authorization')
    qy_pid = request.args.get('imagePid')
    try:
        qr_image = selectImageByPidAndFuid(qy_pid, int(getUidFromToken(user_token)))
        return jsonify({
            'imageData': qr_image.image,
        })
    except:
        return "Token无效"


# POST
def delDiary():
    from Controller.login.getJWTandVerify import getUidFromToken

    # 请求头中的Token
    user_token = request.headers.get('Authorization')
    del_did = request.form.get("delDiaryDid")

    try:
        return delDiaryByDidAndFuid(del_did, int(getUidFromToken(user_token)))
    except:
        return '500'


# 对数据库的操作，根据did和fuid（鉴权）查询日记
def selectDiaryByDid(did, fuid):
    from Pojo import Diary
    from sqlalchemy import and_
    diary = Diary.query.filter(and_(Diary.did == int(did), Diary.fuid == fuid)).first()
    # print(diary)
    # print('--------------------', diary.images)
    return diary

# 对数据库的操作，通过uid和date查询日记
def slelectDiaryByDateAndUid(qy_date, qy_uid):
    # 传入需要查询的日期，以及uid，返回该日的所有日记数据
    # user_token = request.headers.get('Authorization')
    from Pojo import Diary
    from sqlalchemy import and_
    diarys = Diary.query.filter(and_(Diary.createdate == qy_date, Diary.fuid == qy_uid)).all()
    # print(diarys)
    return diarys

# 对数据库的操作，通过pid和fuid获取图片
def selectImageByPidAndFuid(qy_pid, qy_fuid):
    from Pojo import Image
    from sqlalchemy import and_
    image = Image.query.filter(and_(Image.pid == int(qy_pid), Image.fuid == int(qy_fuid))).first()
    # print('---------------------', image)
    return image

# 对数据库的操作，通过did和fuid来删除日记
def delDiaryByDidAndFuid(qy_did, qy_fuid):
    from Pojo import Diary
    from sqlalchemy import and_
    from Pojo import db
    try:
        diary = Diary.query.filter(and_(Diary.did == int(qy_did), Diary.fuid == int(qy_fuid))).first()
        # 删除数据
        db.session.delete(diary)
        # 提交会话 增删改都要提交会话
        db.session.commit()
        return '200'
    except:
        return '500'